package com.ajie.service.impl;

import com.ajie.entity.FeedBack;
import com.ajie.mapper.FeedBackMapper;
import com.ajie.service.FeedBackService;
import com.ajie.utils.PageResult;
import com.ajie.utils.QueryInfo;
import com.ajie.utils.Result;
import com.ajie.utils.SecurityUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class FeedBackServiceImpl implements FeedBackService {
    
    @Autowired
    private FeedBackMapper feedBackMapper;
    
    @Override
    public Result addFeedBack(FeedBack feedBack) {
        String[] arr = feedBack.getPic();
        feedBack.setUid(SecurityUtil.getUserId());
        String picture = "";
        if (arr != null){
            for (int i = 0; i < arr.length; i++) {
                if (i == 0){
                    picture = arr[i];
                }else{
                    picture = picture + "," +  arr[i];
                }
            }
        }
        feedBack.setPicture(picture);
        feedBackMapper.addFeedBack(feedBack);
        return Result.success("添加反馈成功！");
    }
    
    @Override
    public Result findPage(QueryInfo queryInfo) {
        String[] split = queryInfo.getQueryString().split("::");
        List<FeedBack> result = feedBackMapper.findPage(split[0],split[1]);
        result.forEach(item->{
            if (item.getPicture() != null  || item.getPicture().length()>0 ){
                item.setPic(item.getPicture().split(","));
            }
        });
        Page page = new Page(queryInfo.getPageNumber(),queryInfo.getPageSize());
        // 获取list的大小
        int total = result.size();
        page.setTotal(total);
        int startIndex = (queryInfo.getPageNumber()-1) * queryInfo.getPageSize();
        int endIndex = Math.min(startIndex+queryInfo.getPageSize(),total);
        if (startIndex< total){
            page.addAll(result.subList(startIndex,endIndex));
        }
        PageInfo<Object> objectPageInfo = new PageInfo<>(page);
        return new PageResult(total,objectPageInfo.getList());
    }
    
    @Override
    public Result delete(Long id) {
        feedBackMapper.delete(id);
        return Result.success("删除反馈成功！");
    }
}
